import 'dart:async';



class EventBus1 {
  static EventBus1? _eventBus;
  final Map<String, Map<String, StreamController>> _registerMap = new Map<String, Map<String, StreamController>>();

  //默认的广播类型
  final String defName = "default";

  EventBus1._();

  static EventBus1 getDefault() {
    if (_eventBus == null) {
      _eventBus = new EventBus1._();
    }
    return _eventBus!;
  }

  //注册广播的方法-回调的方法-需要广播的界面-广播的类型
  //单个参数
  StreamController registerSingleParameter<T>(String pageName, {String? registerName}) {
    if (null == registerName) {
      registerName = defName;
    }
    if (_registerMap[registerName] == null) {
      Map<String, StreamController> map = Map();
      map[pageName] = StreamController.broadcast();
      _registerMap[registerName] = map;
    } else if (_registerMap[registerName]![pageName] == null) {
      _registerMap[registerName]![pageName] = StreamController<T>();
    }
    return _registerMap[registerName]![pageName]!;
  }

  //注册广播的方法-回调的方法-需要广播的界面-广播的类型
  //无参数
  void registerNoParameter(Function() listener, String pageName, {String? registerName}) {
    if (null == registerName) {
      registerName = defName;
    }
    if (_registerMap[registerName] == null) {
      Map<String, StreamController> map = Map();
      map[pageName] = StreamController.broadcast();
      _registerMap[registerName] = map;
    } else if (_registerMap[registerName]![pageName] == null) {
      _registerMap[registerName]![pageName] = StreamController.broadcast();
    }
    _registerMap[registerName]![pageName]!.stream.listen((msg) {
      if (null == msg) {
        listener();
      } else {
        print("EventBus:post广播不需要参数!!!--请不要传参进入:$pageName,$registerName");
        listener();
      }
    });
  }

  //移除广播的方法-广播的类型-需要广播的界面
  void unRegister({String? registerName, String? pageName}) {
    if (null == registerName) {
      registerName = defName;
    }
    if (null == pageName) {
      if (_registerMap[registerName] != null) {
        _registerMap[registerName]!.clear();
        _registerMap.remove(registerName);
      }
    } else {
      if (_registerMap[registerName] != null && _registerMap[registerName]![pageName] != null) {
        _registerMap[registerName]![pageName]!.close();
        _registerMap[registerName]!.remove(pageName);
      }
    }
  }

  //发送广播-msg消息-广播的类型
  void post<T>({T? msg, String? registerName}) {
    if (null == registerName) {
      registerName = defName;
    }
    if (_registerMap.containsKey(registerName)) {
      _registerMap[registerName]?.forEach((key, value) {
        if (_registerMap[registerName]![key] != null) {
          _registerMap[registerName]![key]!.add(msg);
        }
      });
    }
  }
}
